package com.eric.server.logic;

import com.eric.server.packet.Packet;
import io.netty.channel.Channel;

/**
 * Created by eric on 2017/11/16.
 */
public class IoSession {
    /** 网络连接channel */
    private Channel channel;

    private String user;
    /** 房间号 */
    private String room;

    public IoSession(Channel channel){
        this.channel = channel;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getRoom() {
        return room;
    }

    public void setRoom(String room) {
        this.room = room;
    }

    public void sendPacket(Packet packet){
        if(packet == null) throw new RuntimeException("Packet is null .");
        if(channel == null || !channel.isActive()) throw new RuntimeException("channel is null or not active.");
        channel.writeAndFlush(packet);
    }

    public boolean isClose() {
        if (channel == null) {
            return true;
        }
        return !channel.isActive() ||
                !channel.isOpen();
    }

    public void close() {
        try{
            if (this.channel == null) {
                return;
            }
            if (channel.isOpen()) {
                channel.close();
            }
        }catch(Exception e){
        }
    }
}
